const Router = require('koa-router')
const solc = require('solc')
const web3 = require('./test').web3
const getContract = require('./db').getContract
const saveContract = require('./db').saveContract
const readFile = require('./util').readFile
const writeFile = require('./util').writeFile



const router = new Router()

router.get('/', (ctx, next) => {
  ctx.body = 'hello world'
  next()
})


/*
创建并部署合约
@param  name :string 合约名称
@return address :string 合约地址
*/
router.post('/api/createContract', async (ctx, next) => {
  let { name } = ctx.request.body
  if (name) {
    let contractPath = `./contracts/${name}.sol`
    try{
      // 判断合约是否存在
      let isExists = await getContract(name)
      if (!isExists){
        let source = await readFile('./contractTemplate.sol')
        // 替换其中的合约名称
        source = source.replace('UNIQUE_CONTRACT_NAME', name)
        // 写入到合约文件夹中去
        let isWroten = await writeFile(contractPath, source)
        // 部署
        let compiledCode = solc.compile(source, 1)
        let abiDefinition = JSON.parse(compiledCode.contracts[`:${name}`].interface)
        let deployCode = compiledCode.contracts[`:${name}`].bytecode
        // 合约对象
        let tokenContract = new web3.eth.Contract(abiDefinition)
        // 默认使用第一个用户
        let Addrs = await web3.eth.getAccounts()
        let deployeAddr = Addrs[0]
        // 部署
        let newContractInstance = await tokenContract.deploy({
          data: deployCode,
          arguments: [123]
        }).send({from: deployeAddr, gas: 3141592})

        // 将部署成功的 address 和 name 对应关系放到Sqlite数据库中去
        saveContract(name, newContractInstance.options.address)
        
        ctx.body = {success: true, address: newContractInstance.options.address}
      }else{
        ctx.body = {success: false, errmsg: '合约名称已经存在'}
      }
    }catch(e){
      console.log(e)
      ctx.body = {success: false, errmsg: e.toString()}
    }
  }else{
    ctx.body = {success: false, errmsg: '缺少参数'}
  }
  next()
})



/* 获取合约地址
@param name :string 合约名称
*/
router.get('/api/getContractAddress', async (ctx, next) => {
  let { name } = ctx.query
  if (name) {
    let contract = await getContract(name)
    if (contract) {
      ctx.body = {
        success: true,
        data: {
          address: contract.address
        }
      }
    }else{
      ctx.body = {
        success: false,
        errmsg: '没有该合约信息'
      }
    }
  }
  next()
})



/*
创建帐号
@param name :string 合约名称
@param password :string 密码
*/
router.post('/api/createAccount', async (ctx, next) => {
  let { password } = ctx.request.body
  let wallet = await await web3.eth.personal.newAccount(password)
  ctx.body = {
    success: true,
    data: {
      address: wallet
    }
  }
  next()
})

/*
查询交易信息
@param address :string 交易地址
*/
router.get('/api/getTransactionReceipt', async (ctx, next) => {
  let { address } = ctx.query
  if (address) {
    let receipt = await web3.eth.getTransactionReceipt(address)
    ctx.body = {
      success: true,
      data: receipt
    }
  }else{
    ctx.body = {
      success: false,
      errmsg: '缺少参数'
    }
  }
  next()
})


/*销毁合约
@param name :string 合约名称
销毁合约需要修改Sol
http://liyuechun.org/2017/09/29/solidity-contract-0005/
*/
router.post('/api/destroyContract', async (ctx, next) => {
  // 通过合约地址 -> 拿到合约对象 -> 调用该对象上的某个销毁函数
  next()
})




module.exports = router